/*
 * Copyright (C) 2011 Cyril Mottier (http://www.cyrilmottier.com)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.cyrilmottier.android.gdcatalog;

import greendroid.app.GDMapActivity;
import greendroid.graphics.drawable.DrawableStateSet;
import greendroid.graphics.drawable.MapPinDrawable;
import greendroid.widget.ActionBarItem;
import greendroid.widget.ActionBarItem.Type;
import greendroid.widget.QuickAction;
import greendroid.widget.QuickActionGrid;
import greendroid.widget.QuickActionWidget;
import greendroid.widget.QuickActionWidget.OnQuickActionClickListener;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;

import android.content.Context;
import android.content.res.ColorStateList;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.ColorFilter;
import android.graphics.LightingColorFilter;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Point;
import android.graphics.drawable.Drawable;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.ItemizedOverlay;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;
import com.google.android.maps.OverlayItem;
import com.google.android.maps.Projection;
import com.meiwenhui.android.samples.entites.Coordinate;
import com.orm.androrm.DatabaseAdapter;
import com.orm.androrm.Model;

public class MapPinMapActivity extends GDMapActivity {

	private static Random sRandom = new Random();

	private QuickActionWidget mGrid;
	private QuickActionWidget mBar;
	private LocationManager locationManager;
	private MapView mapView;
	private GeoPoint mGeoPoint;

	private static final int[] PRESSED_STATE = { android.R.attr.state_pressed };

	private static final OverlayItem[] sUSAWestCoast = { new OverlayItem(new GeoPoint(37774900, -122419400), "San Francisco", null),
			new OverlayItem(new GeoPoint(37770600, -119510800), "Yosemite National Park", null),
			new OverlayItem(new GeoPoint(36878200, -121947300), "Monteray Bay", null), new OverlayItem(new GeoPoint(35365800, -120849900), "Morro Bay", null),
			new OverlayItem(new GeoPoint(36936900, -111483800), "Lake Powell", null), };

	private static final OverlayItem[][] sAreas = { sUSAWestCoast };

	// @formatter:on

	private void myLocation() {
		mGeoPoint = getCurrentPoint();// 设置地图的当前位置信息
		MyLocationOverlay myLocationOverlay = new MyLocationOverlay();
		mapView.getOverlays().add(myLocationOverlay);
		mapView.getController().animateTo(mGeoPoint);
	}

	private void myTrack() {
		MyTrackOverlay myOverlay = new MyTrackOverlay();
		mapView.getOverlays().add(myOverlay);
		mapView.refreshDrawableState();
	}

	private void clearTrack() {
		mapView.getOverlays().clear();
		mapView.invalidate();
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Toast.makeText(MapPinMapActivity.this, "正在从服务器上加载数据 ... ", Toast.LENGTH_SHORT).show();
		
		setActionBarContentView(R.layout.map_pin);

		prepareQuickActionGrid();
		addActionBarItem(Type.Edit, R.id.gdi_grid);

		mapView = (MapView) findViewById(R.id.map_view);
		mapView.setBuiltInZoomControls(true);
		mapView.setTraffic(true);

		setOverlays();

		mapView.getController().setCenter(new GeoPoint(36936900, -111483800));
		mapView.getController().setZoom(8);
	}
	
	public void setOverlays(){
		final Resources r = getResources();

		for (int i = 0; i < sAreas.length; i++) {
			final OverlayItem[] items = sAreas[i];

			ColorStateList pinCsl = createRandomColorStateList();
			ColorStateList dotCsl = createRandomColorStateList();
			BasicItemizedOverlay itemizedOverlay = new BasicItemizedOverlay(new MapPinDrawable(r, pinCsl, dotCsl));

			for (int j = 0; j < items.length; j++) {
				itemizedOverlay.addOverlay(items[j]);
			}

			mapView.getOverlays().add(itemizedOverlay);
		}

	}

	public void initDB() {
		List<Class<? extends Model>> models = new ArrayList<Class<? extends Model>>();
		models.add(Coordinate.class);
		DatabaseAdapter.setDatabaseName("android_samples");
		DatabaseAdapter adapter = new DatabaseAdapter(getApplicationContext());
		adapter.setModels(models);

		// insert data
		Coordinate coordinate = new Coordinate();
		coordinate.setLat(1);
		coordinate.setLng(2);
		coordinate.setTime(new Date());
		coordinate.save(this);

	}

	private GeoPoint getCurrentPoint() {
		locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
		Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
		GeoPoint point = null;
		if (location == null) { // 没有最后位置，更新gps,获取当前位置
			locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
			point = new GeoPoint(37774900, -122419400);
		} else { // 当前反馈的GPS位置
			Double lat = location.getLatitude() * 1E6;
			Double lng = location.getLongitude() * 1E6;
			point = new GeoPoint(lat.intValue(), lng.intValue());
		}
		return point;
	}

	// 创建位置监听器
	private LocationListener locationListener = new LocationListener() {
		// 位置发生改变时调用
		@Override
		public void onLocationChanged(Location location) {
			Log.d("Location", "onLocationChanged");
		}

		// provider失效时调用
		@Override
		public void onProviderDisabled(String provider) {
			Log.d("Location", "onProviderDisabled");
		}

		// provider启用时调用
		@Override
		public void onProviderEnabled(String provider) {
			Log.d("Location", "onProviderEnabled");
		}

		// 状态改变时调用
		@Override
		public void onStatusChanged(String provider, int status, Bundle extras) {
			Log.d("Location", "onStatusChanged");
		}
	};

	@Override
	protected boolean isRouteDisplayed() {
		return false;
	}

	public void onShowGrid(View v) {
		mGrid.show(v);
	}

	public void onShowBar(View v) {
		mBar.show(v);
	}

	@Override
	public boolean onHandleActionBarItemClick(ActionBarItem item, int position) {

		switch (item.getItemId()) {
		case R.id.gdi_grid:
			onShowGrid(item.getItemView());
			break;
		default:
			return super.onHandleActionBarItemClick(item, position);
		}

		return true;
	}

	private void prepareQuickActionGrid() {
		mGrid = new QuickActionGrid(this);
		mGrid.addQuickAction(new MyQuickAction(this, R.drawable.gd_action_bar_compose, R.string.my_location));
		mGrid.addQuickAction(new MyQuickAction(this, R.drawable.gd_action_bar_export, R.string.my_track));
		mGrid.addQuickAction(new MyQuickAction(this, R.drawable.gd_action_bar_share, R.string.map));
		mGrid.addQuickAction(new MyQuickAction(this, R.drawable.gd_action_bar_search, R.string.workAddress));

		mGrid.setOnQuickActionClickListener(new OnQuickActionClickListener() {
			public void onQuickActionClicked(QuickActionWidget widget, int position) {
				if (position == 0) {
					myLocation();
				} else if (position == 1) {
					myTrack();
				} else if (position == 2) {
					clearTrack();
				} else if (position == 3) {
					setOverlays();
				} else {
					Toast.makeText(MapPinMapActivity.this, "Item " + position + " clicked", Toast.LENGTH_SHORT).show();
				}
			}
		});
	}

	private static class MyQuickAction extends QuickAction {

		private static final ColorFilter BLACK_CF = new LightingColorFilter(Color.BLACK, Color.BLACK);

		public MyQuickAction(Context ctx, int drawableId, int titleId) {
			super(ctx, buildDrawable(ctx, drawableId), titleId);
		}

		private static Drawable buildDrawable(Context ctx, int drawableId) {
			Drawable d = ctx.getResources().getDrawable(drawableId);
			d.setColorFilter(BLACK_CF);
			return d;
		}

	}

	private class BasicItemizedOverlay extends ItemizedOverlay<OverlayItem> {

		private ArrayList<OverlayItem> mOverlays = new ArrayList<OverlayItem>();

		public BasicItemizedOverlay(Drawable defaultMarker) {
			super(boundCenterBottom(defaultMarker));
		}

		public void addOverlay(OverlayItem overlay) {
			mOverlays.add(overlay);
			populate();
		}

		@Override
		protected OverlayItem createItem(int i) {
			return mOverlays.get(i);
		}

		@Override
		public int size() {
			return mOverlays.size();
		}

		@Override
		protected boolean onTap(int index) {
			return true;
		}

	}

	private ColorStateList createRandomColorStateList() {

		int[][] states = new int[2][];
		int[] colors = new int[2];

		final int randomColor = randomColor();

		states[0] = PRESSED_STATE;
		colors[0] = addRGB(randomColor, -50);

		states[1] = DrawableStateSet.EMPTY_STATE_SET;
		colors[1] = randomColor;

		return new ColorStateList(states, colors);
	}

	private static final int randomColor() {
		int r = sRandom.nextInt(256);
		int g = sRandom.nextInt(256);
		int b = sRandom.nextInt(256);
		return Color.rgb(r, g, b);
	}

	private static int addRGB(int color, int amount) {
		int r = constrain(Color.red(color) + amount, 0, 255);
		int g = constrain(Color.green(color) + amount, 0, 255);
		int b = constrain(Color.blue(color) + amount, 0, 255);
		return Color.rgb(r, g, b);
	}

	public static int constrain(int amount, int low, int high) {
		return amount < low ? low : (amount > high ? high : amount);
	}

	class MyLocationOverlay extends Overlay {
		@Override
		public boolean draw(Canvas canvas, MapView mapView, boolean shadow, long when) {
			super.draw(canvas, mapView, shadow);
			Paint paint = new Paint();
			Point myScreenCoords = new Point();
			// 将经纬度转换成实际屏幕坐标
			mapView.getProjection().toPixels(mGeoPoint, myScreenCoords);
			paint.setStrokeWidth(1);
			paint.setARGB(255, 255, 0, 0);
			paint.setStyle(Paint.Style.STROKE);
			Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.gd_map_pin_pin);
			canvas.drawBitmap(bmp, myScreenCoords.x, myScreenCoords.y, paint);
			// canvas.drawText("中国北京", myScreenCoords.x, myScreenCoords.y,
			// paint);
			return true;
		}
	}

	class MyTrackOverlay extends Overlay {

		@Override
		public void draw(Canvas canvas, MapView mapView, boolean shadow) {
			super.draw(canvas, mapView, shadow);
			// 画笔
			Paint paint = new Paint();
			paint.setColor(Color.RED);
			paint.setDither(true);
			paint.setStyle(Paint.Style.STROKE);
			paint.setStrokeJoin(Paint.Join.ROUND);
			paint.setStrokeCap(Paint.Cap.ROUND);
			paint.setStrokeWidth(2);
			Projection projection = mapView.getProjection();
			Point p1 = new Point();
			Path path = new Path();
			path.moveTo(p1.x, p1.y);
			int index = 0;
			for (OverlayItem overlay : sUSAWestCoast) {
				Point p = new Point();
				projection.toPixels(overlay.getPoint(), p);
				if (index == 0) {
					path.moveTo(p.x, p.y);
					index++;
				}
				path.lineTo(p.x, p.y);
			}
			canvas.drawPath(path, paint);// 画出路径
		}

	}

}
